//
//  adminDataBaseHandle.m
//  真·豆瓣半完全体
//
//  Created by dllo on 16/1/8.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "adminDataBaseHandle.h"
#import "adminModel.h"
#import <sqlite3.h>
@implementation adminDataBaseHandle



+ (adminDataBaseHandle*) sharedAdminDataBaseHandle{
    static adminDataBaseHandle *handle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle = [[adminDataBaseHandle alloc] init];
    });
    return handle;
}

- (void) openDataBase{
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *dbPath = [document stringByAppendingPathComponent:@"Admin.sqlite"];
    NSLog(@"admin沙盒：%@", dbPath);
    int result = sqlite3_open(dbPath.UTF8String, &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"OpenSuccess");
    }
    else{
        NSLog(@"OpenDefeat");
    }
}
- (void) createTable{
    NSString *sqlStr =[ NSString stringWithFormat:@"create table if not exists Admin(number integer primary key autoincrement, name text, code text, email text, phone text)"];
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"CreateSuccess");
    }
    else{
        NSLog(@"CreatDefeat");
    }
}
- (void) insertModel:(adminModel *)model{
    NSString *sqlStr = [NSString stringWithFormat:@"insert into Admin(name, code, email, phone) values('%@', '%@', '%@', '%@')", model.name, model.code, model.email, model.phone];
    int result = sqlite3_exec(dbPoint, sqlStr.UTF8String, NULL, NULL, NULL);
    if (result == SQLITE_OK) {
        NSLog(@"InsertSuccess");
    }
    else{
        NSLog(@"InsertDefeat");
    }
}
- (NSMutableArray *) selectModle{
    NSString *sqlStr = [NSString stringWithFormat:@"select * from Admin"];
    NSMutableArray *arr =[ NSMutableArray array];
    sqlite3_stmt *stmt = nil;
    int result = sqlite3_prepare_v2(dbPoint, sqlStr.UTF8String, -1, &stmt, NULL);
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            const unsigned char *name = sqlite3_column_text(stmt, 1);
            const unsigned char *code = sqlite3_column_text(stmt, 2);
            const unsigned char *email = sqlite3_column_text(stmt, 3);
            const unsigned char *phone = sqlite3_column_text(stmt, 4);
            adminModel *model = [adminModel adminModel];
            model.name = [NSString stringWithUTF8String:(const char*)name];
            model.code = [NSString stringWithUTF8String:(const char*)code];
            model.email = [NSString stringWithUTF8String:(const char*)email];
            model.phone = [NSString stringWithUTF8String:(const char*)phone];
            [arr addObject:model];
        }
    }
    else{
        NSLog(@"SelectDefeat");
    }
    return arr ;
}


@end
